package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * Admin端登录接口
     *
     * @param DTO
     * @return
     */
    @Override
    @Transactional
    public ResponseResult login(AdUserDTO DTO) {

        //1. 检查用户是否存在
        if (DTO == null || StringUtils.isBlank(DTO.getName()) || StringUtils.isBlank(DTO.getPassword())) {
            CustException.cust(AppHttpCodeEnum.TOKEN_INVALID, "无效的参数");
        }
        //2 根据用户名查询用户信息
        LambdaQueryWrapper<AdUser> lambdaQuery = Wrappers.lambdaQuery();
        AdUser adUser = this.getOne(lambdaQuery.eq(AdUser::getName, DTO.getName()));
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        if (9 != adUser.getStatus()) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "用户状态异常,请联系管理员");
        }
        //3 获取数据库密码和盐， 匹配密码
        String password = adUser.getPassword();
        String salt = adUser.getSalt();
        //用户输入密码,加密后
        String newPwd = DigestUtils.md5DigestAsHex((DTO.getPassword() + salt).getBytes());
        if (!newPwd.equals(adUser.getPassword())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "密码错误");
        }
        //修改最新登陆时间
        adUser.setLoginTime(new Date());
        this.updateById(adUser);
        //5. 颁发token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        // 用户信息返回 VO
        AdUserVO vo = new AdUserVO();
        BeanUtils.copyProperties(adUser, vo);
        Map map = new HashMap();
        //6 返回结果（jwt）
        map.put("token", token);
        map.put("user", vo);
        return ResponseResult.okResult(map);
    }
}